

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class BilletterieImpl implements Billetterie {

	//attribut
	/**
	 * variable partagé du côté serveur
	 * dont l'utilisation sera synchronosé
	 */
	private int nbTiketsDispo;

	@Override
	public synchronized void reservation(int nbBillet) {

		System.out.println("Reservation "+ Thread.currentThread().getName());
		while ( nbBillet > this.nbTiketsDispo )
			//System.out.println("Mise en attente(manque de bille "+ Thread.currentThread().getName());
			try {
				wait();
			} catch (InterruptedException e) {}

		this.nbTiketsDispo -= nbBillet;
		System.out.println("Fin Reservation "+ Thread.currentThread().getName());
	}

	@Override
	public synchronized void ajouterTickets(int nbBillet) {
		System.out.println("Ajout ticket "+ Thread.currentThread().getName());
		this.nbTiketsDispo += nbBillet;
		notifyAll();
		System.out.println("Fin Ajout "+ Thread.currentThread().getName());

	}
	public static void main(String[] args) {
		System.out.println("Installation du security Manager ");
		if(System.getSecurityManager() == null)
			System.setSecurityManager(new SecurityManager());
		System.out.println("fait!");

		Billetterie billetterie = new BilletterieImpl();

		try {
			Billetterie stub = (Billetterie)UnicastRemoteObject.exportObject(billetterie,0);			

			Registry r =LocateRegistry.createRegistry(1099);
			r.rebind("billetterie", stub);

		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	@Override
	public int getNbTiketsDispo() {
		return nbTiketsDispo;
	}

}
